package com.google.persist;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

@Component
public class AutoPersist {
    private final Logger Log = LoggerFactory.getLogger(AutoPersist.class);

    public  <T> T BuildBean(Class<T> clazz,JSONObject jsonObject) throws Exception{
                Field[] fileds=clazz.getDeclaredFields();
        T newObject= null;
        try {
            newObject = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        try {
            for(Field field:fileds) {
                String str=toUpperCaseFirstOne(field.getName());
                Method method= null;
                Method getMethod= null;
                try {
                    method = clazz.getMethod(String.format("set%s",str),field.getType());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                if(jsonObject.get(field.getName())==null || jsonObject.get(field.getName()).toString().equals("") || jsonObject.get(field.getName()).toString().equals("null")){
                    if(field.getName().equals("id")){
                        method.invoke(newObject, UUID.randomUUID().toString().replace("-",""));
                    }else{
                        method.invoke(newObject, (Object) null);
                    }
                }else{
                    if(field.getType().getName().equals("java.sql.Timestamp") ){
                        try {
                            Long time = JSONObject.fromObject(jsonObject.get(field.getName())).getLong("time");
                            Timestamp timestamp=new Timestamp(time);
                            method.invoke(newObject,timestamp);
                        } catch (Exception e) {
                            Timestamp timestamp = Timestamp.valueOf(jsonObject.get(field.getName()).toString());
                            method.invoke(newObject,timestamp);
                        }
                    }else if(field.getType().getName().equals("java.math.BigDecimal")){
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(jsonObject.get(field.getName())));
                        method.invoke(newObject,bigDecimal);
                    }else if(jsonObject.get(field.getName()).getClass().getName().equals("java.lang.Long") && field.getType().getName().equals("java.lang.Integer") ){
                        throw new Exception(field.getName()+"的值超出了Integer的范围，请在Entity中将字段类型改为Long");
                    }else{
                        method.invoke(newObject,jsonObject.get(field.getName()));
                    }
                }
            }
        } catch (Exception e){
            e.printStackTrace();
            Log.error("自动持久化有异常");
            throw  e;
        }
        return  newObject;
    }

    private static String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

}
